#!/usr/bin/env python3
"""
检查浏览器控制台错误的脚本
使用requests-html来执行JavaScript并获取控制台日志
"""

import requests
import time
import re

def check_page_with_js():
    """检查页面并执行JavaScript"""
    print("🌐 正在访问页面并检查JavaScript执行...")
    
    try:
        # 获取页面内容
        response = requests.get("http://localhost:5173", timeout=10)
        if response.status_code != 200:
            print(f"❌ 页面访问失败: {response.status_code}")
            return
        
        print("✅ 页面访问成功")
        
        # 检查页面源码
        content = response.text
        print(f"📊 页面内容长度: {len(content)} 字符")
        
        # 检查是否有React相关的错误信息
        error_patterns = [
            r'error[^>]*>([^<]+)',
            r'Error[^>]*>([^<]+)',
            r'TypeError[^>]*>([^<]+)',
            r'ReferenceError[^>]*>([^<]+)',
            r'SyntaxError[^>]*>([^<]+)'
        ]
        
        found_errors = []
        for pattern in error_patterns:
            matches = re.findall(pattern, content, re.IGNORECASE)
            found_errors.extend(matches)
        
        if found_errors:
            print("⚠️  发现可能的错误信息:")
            for error in found_errors:
                print(f"  - {error}")
        else:
            print("✅ 未发现明显的错误信息")
        
        # 检查JavaScript文件是否包含错误
        js_files = [
            "/src/main.tsx",
            "/src/App.tsx"
        ]
        
        for js_file in js_files:
            try:
                js_response = requests.get(f"http://localhost:5173{js_file}", timeout=5)
                if js_response.status_code == 200:
                    js_content = js_response.text
                    
                    # 检查是否有明显的语法错误
                    if "import" in js_content and "from" in js_content:
                        print(f"✅ {js_file}: 包含import语句")
                    
                    # 检查是否有未定义的变量
                    if "undefined" in js_content.lower():
                        print(f"⚠️  {js_file}: 可能包含undefined引用")
                    
                    # 检查是否有TypeScript错误
                    if "any" in js_content and ":" in js_content:
                        print(f"ℹ️  {js_file}: 包含TypeScript类型")
                        
                else:
                    print(f"❌ {js_file}: 无法访问 ({js_response.status_code})")
            except Exception as e:
                print(f"❌ {js_file}: 检查时出错 - {e}")
        
        # 检查根元素
        root_match = re.search(r'<div id="root">(.*?)</div>', content, re.DOTALL)
        if root_match:
            root_content = root_match.group(1).strip()
            if root_content:
                print(f"🎯 根元素有内容: {root_content[:100]}...")
            else:
                print("❌ 根元素为空")
        else:
            print("❌ 未找到根元素")
            
    except Exception as e:
        print(f"❌ 检查页面时出错: {e}")

def main():
    """主函数"""
    print("🚀 开始检查页面JavaScript执行状态...")
    check_page_with_js()
    print("\n✅ 检查完成")

if __name__ == "__main__":
    main()
